<template>

  <popup :title="title" @confirm="handleSubmit" ref="popupRef">

    <el-form :model="formData" :rules="rules" ref="formRef" label-width="10%">
      <el-form-item label="名称" prop="name">
        <el-input
            class="ls-input"
            v-model="formData.name"
            placeholder="请输入名称"
            clearable
        />
      </el-form-item>

      <el-form-item label="账号" prop="account" v-if="title === 'add'">
        <el-input
            class="ls-input"
            v-model="formData.account"
            placeholder="请输入账号"
            clearable
        />
      </el-form-item>

      <el-form-item label="密码" prop="password" v-if="title === 'add'">
        <el-input
            class="ls-input"
            v-model="formData.password"
            placeholder="请输入密码"
            clearable
        />
      </el-form-item>

      <el-form-item label="备注" prop="memo">
        <el-input
            v-model="formData.memo"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="请输入备注"
            maxlength="200"
            show-word-limit
        />
      </el-form-item>
    </el-form>

  </popup>

</template>

<script setup>
import popup from '@/components/popup/index.vue'
import {reactive, ref, shallowRef} from "vue";
import {add, edit} from '@/api/user'
import FormInstance from 'element-plus'

const formRef = shallowRef(FormInstance)
const popupRef = shallowRef(popup)
const emit = defineEmits(['success'])

const title = ref('edit')
const formData = reactive({
  id: 0,
  name: '',
  account: '',
  password: '',
  memo: '',
})

const rules = reactive({
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 3, message: '长度必须大于3', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, message: '长度必须大于3', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, message: '长度必须大于3', trigger: 'blur' },
  ],
})

const handleSubmit = async () => {
  await formRef.value?.validate()
  title.value === 'edit' ? await edit(formData) : await add(formData)
  emit('success')
}

const setFormData = async (data = {}, name = 'add') => {
  title.value = name

  if (Object.keys(data).length > 0) {
    for (const key in formData) {
      if (data[key] !== null && data[key] !== undefined) {
        formData[key] = data[key]
      }
    }
  }
}

defineExpose({
  setFormData
})
</script>

<style scoped>

</style>